/**
 * 
 */
package ar.com.jwa.services;

import java.io.InputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.springframework.beans.factory.annotation.Autowired;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import ar.com.jwa.domain.User;

/**
 * @author ngonzalez
 *
 */
public class DataBaseLoaderTestCase extends ServiceTestCase {
	
	@Autowired
	private UserLocalService userLocalService;
	
	public void testGenerateAllUsers(){
		
		try {
			  
			  User user;
			  
			  InputStream io = ClassLoader.getSystemResourceAsStream("dataBaseLoaderUserInfo.xml");

			  DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			  
			  DocumentBuilder db = dbf.newDocumentBuilder();
			  
			  Document doc = db.parse(io);
			  
			  doc.getDocumentElement().normalize();
			  
			  NodeList nodeLst = doc.getElementsByTagName("player");

				if (nodeLst != null && nodeLst.getLength() > 0) {
	
					for (int i = 0; i < nodeLst.getLength(); i++) {
	
						Element el = (Element) nodeLst.item(i);
	
						user = getUser(el);
	
						this.getUserLocalService().saveUser(user);
					}
				}
			  
		} catch (Exception e) {
			    e.printStackTrace();
			    fail(e.getMessage());
		}
	}
	
	
	/**
	 * I take an User element and read the values in, create
	 * an User object and return it
	 */
	private User getUser(Element userNode) {

		String name = getTextValue(userNode,"name");
		String lastName = getTextValue(userNode,"lastName");
		String nickName = getTextValue(userNode,"nickName");
		String password = getTextValue(userNode,"password");
		String mail = getTextValue(userNode,"mail");
		String cellphone = getTextValue(userNode,"cellphone");
		
		User user = new User(name,lastName,nickName,password,mail,cellphone);

		return user;
	}
	
	/**
	 * I take a xml element and the tag name, look for the tag and get
	 * the text content
	 * i.e for <player><name>John</name></player> xml snippet if
	 * the Element points to user node and tagName is 'name' I will return John
	 */
	private String getTextValue(Element ele, String tagName) {
		String textVal = null;
		NodeList nl = ele.getElementsByTagName(tagName);
		if(nl != null && nl.getLength() > 0) {
			Element el = (Element)nl.item(0);
			textVal = el.getFirstChild().getNodeValue();
		}
		return textVal;
	}

	
	public void testGenerateTestGames(){
		
	}
	
	
	
	
	/**
	 * @return the userLocalService
	 */
	public UserLocalService getUserLocalService() {
		return userLocalService;
	}


	/**
	 * @param userLocalService the userLocalService to set
	 */
	public void setUserLocalService(UserLocalService userLocalService) {
		this.userLocalService = userLocalService;
	}
}
